import { defineStore } from 'pinia'
import { login as loginApi } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    username: localStorage.getItem('username') || '',
    avatar: localStorage.getItem('avatar') || ''
  }),

  actions: {
    async login(username, password) {
      try {
        const { data } = await loginApi(username, password)
        this.token = data.token
        this.username = data.username
        this.avatar = data.avatar
        
        localStorage.setItem('token', data.token)
        localStorage.setItem('username', data.username)
        localStorage.setItem('avatar', data.avatar)
        
        return true
      } catch (error) {
        ElMessage.error(error.message || '登录失败')
        return false
      }
    },

    logout() {
      this.token = ''
      this.username = ''
      this.avatar = ''
      
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      localStorage.removeItem('avatar')
    }
  }
}) 